package pers.zifeng.distributed.lock.redis.event;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import pers.zifeng.distributed.lock.common.MysqlService;
import pers.zifeng.distributed.lock.utils.PropertiesReader;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.util.Properties;

/**
 * @author: zf
 * @date: 2021/06/04 09:24:53
 * @version: 1.0.0
 * @description: 基于Redisson实现的分布式锁
 */
@Slf4j
public class RedissonLock {
    private static final String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];

    public static void buyMaskWithLock(RedissonClient client) {
        RLock lock = null;
        try {
            while (true) {
                lock = client.getLock("buyMask");
                log.info("【当前线程:" + pid + "】 尝试获取锁！");
                lock.lock();
                log.info("【当前线程:" + pid + "】 获取锁成功！");
                // 抢购口罩
                if (!MysqlService.buyMask()) {
                    break;
                }
                lock.unlock();
                log.info("【当前线程:" + pid + "】 锁释放！");
            }
        } catch (Exception e) {
            log.error("抢购口罩失败！", e);
        } finally {
            if (lock != null) {
                lock.unlock();
                log.info("【当前线程:" + pid + "】 锁释放！");
            }
        }
    }

    public static void main(String[] args) throws IOException {
        Properties properties = PropertiesReader.getProperties("redis.properties");
        Config config = new Config();
        config.useSingleServer().setAddress("redis://" + properties.getProperty("ip") + ":" + properties.getProperty("port"));

        final RedissonClient client = Redisson.create(config);
        buyMaskWithLock(client);
        client.shutdown();
    }

}
